package cn.woblog.android.http.callback;

import com.alibaba.fastjson.JSON;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import cn.woblog.android.http.AppException;
import cn.woblog.android.http.Http;
import cn.woblog.android.http.RequestTask;

public abstract class JSONCallback<T> extends AbstractCallback<T> {
	private Class<T> entityClass;
	private boolean isArray;

	@SuppressWarnings("unchecked")
	public JSONCallback(boolean isArray) {
		this.isArray = isArray;
		//		java.lang.reflect.Type genType = getClass().getGenericSuperclass();
		//		ParameterizedType type = (ParameterizedType) genType;
		//		Class<T> clazz = (Class<T>) type.getActualTypeArguments()[0].getClass();
		//		entityClass = (Class<T>) type.getActualTypeArguments()[0];
		java.lang.reflect.Type genType = getClass().getGenericSuperclass();
		ParameterizedType type = (ParameterizedType) genType;
		Class<T> clazz = (Class<T>) type.getActualTypeArguments()[0].getClass();
		if (ParameterizedType.class.isAssignableFrom(clazz)) {
			ParameterizedType type2 = (ParameterizedType) type.getActualTypeArguments()[0];
			entityClass = (Class<T>) type2.getActualTypeArguments()[0];
		} else {
			entityClass = (Class<T>) type.getActualTypeArguments()[0];
		}
	}

	public JSONCallback() {
		this(false);
	}

	@Override
	public T bindData(Response response, Request request, RequestTask<T> task) throws AppException {
		T t = null;
		if (response.isSuccessful()) {
			try {
				String string = response.body().string();
				if (isCache()) {
					Http.getCacheControl().setCacheString(request.urlString(), getCacheKey(), string);
				}
				t = handleData(string);
			} catch (IOException e) {
				e.printStackTrace();
				throw new AppException(e);
			}
		}
		return t;
		//		if (response.isSuccessful()) {
		//			if (isArray) {
		//				InputStream is = response.body().byteStream();
		//				int len = 0;
		//				long progress = 0;
		//				byte[] buffer = new byte[4096];
		//				StringBuffer sb = new StringBuffer();
		//				while ((len = is.read(buffer)) != -1) {
		//					sb.append(new String(buffer, 0, len));
		//				}
		//				return (T) JSON.parseArray(response.body().string(), entityClass);
		//			} else {
		//				return JSON.parseObject(response.body().bytes(), entityClass);
		//			}
		//		}
		//		return null;
	}

	private T handleData(String string) throws AppException {
		if (isArray) {
			return (T) JSON.parseArray(string, entityClass);
		} else {
			return JSON.parseObject(string, entityClass);
		}
	}

	@Override
	public T bindData(String response, RequestTask<T> t) throws AppException {
		return handleData(response);
	}

}
